package com.easybenefit.UUService.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.easybeanfit.UUService.commutill.UUDialogUtill;
import com.easybeanfit.UUService.commutill.UUJsonUtil;
import com.easybeanfit.UUService.commutill.UUNetUtill;
import com.easybeanfit.UUService.commutill.UUSharedUtil;
import com.easybeanfit.UUService.commutill.UUToastUtil;
import com.easybeanfit.UUService.config.UUConfig;
import com.easybeanfit.UUService.config.UUDict;
import com.easybenefit.UUService.BaseActivity;
import com.easybenefit.UUService.R;
import com.easybenefit.UUService.adapter.MerchantsListAdapter;
import com.easybenefit.UUService.model.HttpAllType;
import com.easybenefit.UUService.model.HttpMerchantBean;
import com.easybenefit.UUService.model.MerchantBean;
import com.easybenefit.UUService.model.UserInfo;
import com.easybenefit.UUService.myinterface.IActivityInterface;
import com.easybenefit.UUService.screenmenu.DoubleListFilterView;
import com.easybenefit.UUService.screenmenu.ExpandMenuView;
import com.easybenefit.UUService.screenmenu.SingleListFilterView;
import com.easybenefit.UUService.xlist.XListView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;

import java.util.ArrayList;
import java.util.List;

/**
 * 商户列表
 */
public class MerchantsListActivity extends BaseActivity implements IActivityInterface, View.OnClickListener {
    private TextView tv_title;//标题
    private XListView xListView;
    private MerchantsListAdapter merchantsListAdapter;
    private Button btn_back;
    private List<MerchantBean> list;
    private int page = 1;
    private int rows = 10;
    private Context context;
    private ExpandMenuView expandMenuView;
    private ProgressDialog progressDialog;
    /**
     * 刷新数据锁
     */
    private boolean isRefresh = true;
    //行业选项
    private ArrayList<String> industries;
    private SparseArray<List<String>> industriechildren;
    private List<HttpAllType.DataBean.ListBean> industriseData;
    //区域
    private ArrayList<String> areaIndustries;
    private SparseArray<List<String>> areaIndustrieschildren;
    private List<HttpAllType.DataBean.ArealistBean> areaData;
    //排序
    private List<String> orderIndustries;
    private List<HttpAllType.DataBean.OrderlistBean> orderData;
    private ArrayList<View> mViewArray;
    private String btype;
    private String type;
    private String area;
    private String district;
    private String order;
    private int p;
    private String maxid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchants_list);
        initView();
        initData();
        initListener();
    }

    /**
     * 监听list事件
     */
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(context, MerchantsDetailActivity.class);
            intent.putExtra("id", list.get(position - 1).getMer_id());
            startActivity(intent);
        }
    };

    @Override
    public void initData() {
        context = this;
        list = new ArrayList<>();
        tv_title.setText(getResources().getText(R.string.merchants_list_title));
        merchantsListAdapter = new MerchantsListAdapter(list, context);
        xListView.setAdapter(merchantsListAdapter);
        industries = new ArrayList<>();
        industriechildren = new SparseArray<List<String>>();
        areaIndustrieschildren = new SparseArray<List<String>>();
        areaIndustries = new ArrayList<>();
        orderIndustries = new ArrayList<>();
        p = 1;
        getAllTypeData();
        getMerchantsData();
    }

    @Override
    public void initView() {
        xListView = (XListView) findViewById(R.id.xlist_coupons);
        tv_title = (TextView) findViewById(R.id.top_title);
        btn_back = (Button) findViewById(R.id.btn_back);
        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);
        expandMenuView = (ExpandMenuView) findViewById(R.id.expandTabView);
    }

    /**
     * 加载结束需要执行的方法
     */
    public void onload() {
        xListView.stopRefresh();
        xListView.stopLoadMore();
        xListView.setRefreshTime();
    }

    @Override
    public void initListener() {
        btn_back.setOnClickListener(this);
        xListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                p = 1;
                list.clear();
                maxid = null;
                if (isRefresh) {
                    isRefresh = false;
                    getMerchantsData();
                }
            }

            @Override
            public void onLoadMore() {
                p++;
//                if (list.size() > 1) {
//                    maxid = list.get(list.size() - 1).getMer_id();
//                } else {
//                    maxid = null;
//                }
                getMerchantsData();
            }
        });
        xListView.setOnItemClickListener(onItemClickListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                MerchantsListActivity.this.finish();
                break;

        }
    }

    /**
     * 获取筛选信息
     */
    public void getAllTypeData() {
        if (!UUNetUtill.isConnected(MerchantsListActivity.this)) {
            UUToastUtil.showToast(MerchantsListActivity.this, UUDict.NOT_INTERNET);
        } else {
            String url = UUConfig.SERVER_BASE_URL + "alltypelist";
            RequestParams params = new RequestParams();

            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {

                }

                @Override
                public void onFinish() {
                    isRefresh = true;
                    onload();
                }

                @Override
                public void onSuccess(int m, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    HttpAllType httpAllType = (HttpAllType) UUJsonUtil.fromJson(content, HttpAllType.class);
                    // 提取并设置数据
                    industriseData = httpAllType.getData().getList();
                    for (int i = 0; i < industriseData.size(); i++) {
                        industries.add(industriseData.get(i).getName());
                        List<HttpAllType.DataBean.ListBean> citys = industriseData.get(i).getTypelist();
                        List<String> items = new ArrayList<String>();
                        if (citys == null || citys.size() == 0) {
                            industriechildren.put(i, null);
                            continue;
                        }
                        for (int j = 0; j < citys.size(); j++) {
                            items.add(citys.get(j).getName());
                        }
                        industriechildren.put(i, items);
                    }
                    final DoubleListFilterView industryFilterView = new DoubleListFilterView(context, "行业筛选", industries, industriechildren, 0, 0);
                    industryFilterView.setOnSelectListener(new DoubleListFilterView.OnSelectListener() {

                        @Override
                        public void getValue(String showText, int superPosition, int position) {
                            btype = industriseData.get(superPosition).getId();
                            if (industriseData.get(superPosition).getTypelist().size() > 0) {
                                type = industriseData.get(superPosition).getTypelist().get(position).getId();
                                setExpandMenuViewTitle(industryFilterView, industriseData.get(superPosition).getTypelist().get(position).getName());
                            } else {
                                type = null;
                                setExpandMenuViewTitle(industryFilterView, industriseData.get(superPosition).getName());
                            }
                            p = 1;
                            getMerchantsData();
                        }
                    });
                    areaData = httpAllType.getData().getArealist();
                    for (int i = 0; i < areaData.size(); i++) {
                        areaIndustries.add(areaData.get(i).getName());
                        List<HttpAllType.DataBean.ArealistBean> citys = areaData.get(i).getTypelist();
                        List<String> items = new ArrayList<String>();
                        if (citys == null || citys.size() == 0) {
                            areaIndustrieschildren.put(i, null);
                            continue;
                        }
                        for (int j = 0; j < citys.size(); j++) {
                            items.add(citys.get(j).getName());
                        }
                        areaIndustrieschildren.put(i, items);
                    }
                    final DoubleListFilterView areaFilterView = new DoubleListFilterView(context, "区域筛选", areaIndustries, areaIndustrieschildren, 0, 0);
                    areaFilterView.setOnSelectListener(new DoubleListFilterView.OnSelectListener() {

                        @Override
                        public void getValue(String showText, int superPosition, int position) {
                            area = areaData.get(superPosition).getId();
                            if (areaData.get(superPosition).getTypelist().size() > 0) {
                                district = areaData.get(superPosition).getTypelist().get(position).getId();
                                setExpandMenuViewTitle(areaFilterView, areaData.get(superPosition).getTypelist().get(position).getName());
                            } else {
                                district = null;
                                setExpandMenuViewTitle(areaFilterView, areaData.get(superPosition).getName());
                            }
                            p = 1;
                            getMerchantsData();

                        }
                    });
                    orderData = httpAllType.getData().getOrderlist();
                    for (int i = 0; i < orderData.size(); i++) {
                        orderIndustries.add(orderData.get(i).getName());
                    }
                    final SingleListFilterView sortFilterView = new SingleListFilterView(context, orderIndustries, "排序筛选");
                    sortFilterView.setOnSelectListener(new SingleListFilterView.OnSelectListener() {

                        @Override
                        public void getValue(String showText, int position) {
                            order = orderData.get(position).getId();
                            setExpandMenuViewTitle(sortFilterView, orderData.get(position).getName());
                            getMerchantsData();
                            p = 1;

                        }
                    });
                    mViewArray = new ArrayList<View>();
                    mViewArray.add(industryFilterView);
                    mViewArray.add(areaFilterView);
                    mViewArray.add(sortFilterView);

                    ArrayList<String> mTextArray = new ArrayList<String>();
                    mTextArray.add("全部行业");
                    mTextArray.add("全城");
                    mTextArray.add("默认排序");

                    //给组合控件设置数据
                    expandMenuView.setValue(mTextArray, mViewArray);
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }

    public void setExpandMenuViewTitle(View view, String showText) {
        int position = getPositon(view);
        if (position >= 0)
            expandMenuView.setTitle(showText, position);
        expandMenuView.closeView();
    }

    public void getMerchantsData() {

        if (!UUNetUtill.isConnected(MerchantsListActivity.this)) {
            UUToastUtil.showToast(MerchantsListActivity.this, UUDict.NOT_INTERNET);
        } else {
            String url = UUConfig.SERVER_BASE_URL + "unionlist";
            RequestParams params = new RequestParams();
            UserInfo userInfo = (UserInfo) UUSharedUtil.getObject(context, UUConfig.UU_USERINFO_NAME, UserInfo.class);
            params.put("mer_id", userInfo.getMer_id());
            params.put("btype", btype);
            params.put("type", type);
            params.put("area", area);
            params.put("district", district);
            params.put("order", order);
            params.put("p", p + "");
            params.put("maxid", maxid);
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(context, "正在获取数据请稍后...");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                    isRefresh = true;
                    onload();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    if (p == 1) {
                        list.clear();
                    }
                    String content = new String(bytes);
                    HttpMerchantBean responseBean = (HttpMerchantBean) UUJsonUtil.fromJson(content, HttpMerchantBean.class);
                    if (responseBean.getData().getMerchantlist().size() > 0) {
                        list.addAll(responseBean.getData().getMerchantlist());
                    } else {
                        UUToastUtil.showToast(context, responseBean.getMessage());
                    }
                    maxid = responseBean.getMaxid();
                    merchantsListAdapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

                }
            });
        }
    }

    /**
     * 获取当前点击的位置
     *
     * @param tView
     * @return
     */
    private int getPositon(View tView) {
        for (int i = 0; i < mViewArray.size(); i++) {
            if (mViewArray.get(i) == tView)
                return i;
        }

        return -1;
    }
}
